package com.example.chessapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RateListActivity2 extends AppCompatActivity implements Runnable{

    Handler handler;
    public static final String  TAG = "RateListActivity2";
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Thread t = new Thread(this);
        t.start();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate_list2);

        //buton先不用
        ListView listView = findViewById(R.id.RateList);

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what==7){
                    ArrayList<String> list2 = (ArrayList<String>)msg.obj;
                    ListAdapter adapter = new ArrayAdapter<String>(RateListActivity2 .this,
                            android.R.layout.simple_list_item_1,list2);
                    listView.setAdapter(adapter);
                }
                super.handleMessage(msg);
            }
        };

    }

    @Override
    public void run() {
        Log.i(TAG,"aaa");
        List<String> ret = new ArrayList<String>();
        try{
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/index.html").get();
            Log.i(TAG,"title:"+doc.title());
            Element table = doc.getElementsByTag("table").get(1);
            Elements trs = table.getElementsByTag("tr");
            for(Element tr:trs){
                Elements tds = tr.getElementsByTag("td");
                if(tds.size()>0){
                    String str = tds.get(0).text();
                    String val = tds.get(5).text();
                    Log.i(TAG,"run: td1="+str+"-->"+val);
                    ret.add(str+"-->"+val);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        //返回消息到主线程
        Message msg = handler.obtainMessage(7,ret);
        handler.sendMessage(msg);
    }
}